<?php
/* ******************************
 *	Product Catalog aJax actions
 * ******************************
 */

set_time_limit(0);

include('../../includes/classes/core.php');
include('../../includes/classes/logger.class.php');
include('../../includes/classes/log.class.php');
include('../../includes/classes/category.tree.class.php');

$log 		= new log();

$action		= $_REQUEST['act'];
$error		= '';
$data		= '';
$user_id	= $_COOKIE['USERID'];


$_log   = Logger::instance('../../log/view/catalog/', Logger::OFF);

switch ($action) {
    case 'get_add_page':
		$page		= GetPage();
		$data		= array('page'	=> $page);
		
        break;
    case 'get_edit_page':
	    $prod_id	= $_REQUEST['id'];
		$page		= GetPage(GetProduct($prod_id));
        
        $data 		= array('page'	=> $page);
        
        break;
    case 'get_list':
	    $count = $_REQUEST['count'];
	    $hidden = $_REQUEST['hidden'];
	    
	    $rResult = mysql_query("SELECT 		`production`.`id`,
											`production`.`code`,
	    									`production`.`name`,
	    									`production_category`.`name`,
	    									`model`.`name`,
	    									`production`.`engine`,
	    									`production`.`engine_capacity`,
	    									`production`.`born_date`,
	    									`production`.`size`,
	    									`brand`.`name`,
											`production`.`barcode`,
											`production`.`comment`
								FROM 		`production` 
								LEFT JOIN 	`production_category` ON `production`.`category` = `production_category`.`id`
								LEFT JOIN 	`model` ON `production`.`model` = `model`.`id`
	    						LEFT JOIN 	`brand` ON `production`.`brand_id` = `brand`.`id`
								WHERE		`production`.`actived` = 1");
		
		$data = array(
			"aaData"	=> array()
		);
		
		while ( $aRow = mysql_fetch_array( $rResult ) )
		{
			$row = array();
			for ( $i = 0 ; $i < $count ; $i++ )
			{
				/* General output */
				$row[] = $aRow[$i];
				if($i == ($count - 1)){
					$row[] = '<input type="checkbox" name="check_' . $aRow[$hidden] . '" class="check" value="' . $aRow[$hidden] . '" />';
				}
			}
			$data['aaData'][] = $row;
		}
		
		$_log->logInfo('get_list');

        break;
    case 'save_prod':
		$prod_id 		= $_REQUEST['id'];
		
		$arr = array(
				//Main
				'code'				=> htmlspecialchars($_REQUEST['code'], ENT_QUOTES),
				'barcode'			=> $_REQUEST['barcode'],
				'name'				=> htmlspecialchars($_REQUEST['name'], ENT_QUOTES),
				'category'			=> $_REQUEST['category'],
				'model'				=> $_REQUEST['model'],
				'engine'	 		=> $_REQUEST['engine'],
				'engine_capacity'	=> $_REQUEST['engine_capacity'],
				'size'				=> $_REQUEST['size'],
				'born_date'			=> $_REQUEST['born_date'],
				'brand_id'			=> $_REQUEST['brand_id'],
				'unit'				=> $_REQUEST['unit'],
				
		
				'comment'			=> htmlspecialchars($_REQUEST['comment'], ENT_QUOTES),
				'image'				=> $_REQUEST['img']
		);
		
		if($prod_id == ''){
			if(!CheckProductExist($arr['name'])){			
				if(!CheckProductCode($arr['code'])){
					AddProduct($user_id, $arr);
				} else {
					$error = 'პროდუქტი ასეთი კოდით უკვე არის სიაში!';
				}
			} else {
				$error = '"' . $arr['name'] . '" უკვე არის სიაში!';
			}
		}else{
			SaveProduct($prod_id, $user_id, $arr);
		}
		
        break;
    case 'disable':
		$prod_id 		= $_REQUEST['id'];
		DisableProduct($prod_id);		
		
        break;
    case 'delete_image':
		$prod_id 		= $_REQUEST['id'];
		DeleteImage($prod_id);		
		
        break;
    case 'clear':
		$file_list = $_REQUEST['file'];
		ClearProduct();
		if (!empty($file_list)) {
			$file_list = ClearFiles(json_decode($file_list));
		}
		$data = array('file_list' => json_encode($file_list));
		
        break;
    default:
       $error = "Action is Null";
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	Product Catalog Functions
 * ******************************
 */

function ClearProduct() {
    $req = mysql_query("SELECT	`id`,
    							`name`
						FROM `production`");
    
    while( $res = mysql_fetch_assoc($req)){
    	$name = htmlspecialchars($res[name], ENT_QUOTES);
    	
    	
    	
    	mysql_query("	UPDATE
							`production`
						SET
							`name`	= '$name'
						WHERE
							`id`	= $res[id]");
    	
    }
}

function ClearFiles($file_list) {
	$array = array();
	foreach ($file_list as $file) {
		if($file != '0.jpg' && $file != 'index.html'){
			$req = mysql_query("SELECT	`id`
								FROM	`production`
								WHERE	`image` = '$file'");
			if (mysql_num_rows($req) == 0){
				$array[] = $file;
			}
		}
	}
	return $array;
}

function AddProduct($user_id, $arr){
	
	mysql_query("INSERT INTO `production` 
						(`user_id`, `code`, `barcode`, `name`, `category`, `model`, `engine`, `engine_capacity`, `size`, `unit`, `brand_id`, `born_date`, `image`, `comment`, `actived`) 
					VALUES 
					  	('$user_id', '$arr[code]', '$arr[barcode]', '$arr[name]', '$arr[category]', '$arr[model]', '$arr[engine]', '$arr[engine_capacity]', '$arr[size]','$arr[unit]', '$arr[brand_id]', '$arr[born_date]', '$arr[image]', '$arr[comment]', 1);");
}

function SaveProduct($prod_id, $user_id, $arr){
	
	mysql_query("UPDATE `production` 
							SET `user_id`		 ='$prod_id', 
								`code`			 ='$arr[code]', 
								`barcode`		 ='$arr[barcode]', 
								`name`			 ='$arr[name]', 
								`category`		 ='$arr[category]', 
								`model`			 ='$arr[model]', 
								`engine`   		 ='$arr[engine]', 
								`engine_capacity`='$arr[engine_capacity]', 
								`size`			 ='$arr[size]',
								`unit`			 ='$arr[unit]', 
								`brand_id`		 ='$arr[brand_id]', 
								`born_date`		 ='$arr[born_date]', 
								`image`			 ='$arr[image]',
								`comment`		 ='$arr[comment]' 
								
					WHERE (`id`='$prod_id');");
	
}

function CheckProductExist($prod_name) 
{
    $res = mysql_fetch_assoc(mysql_query("SELECT `id`
										  FROM `production`
										  WHERE `name` = '$prod_name' && `actived` = 1"));
	if($res['id'] != ''){
		return true;
	}
	return false;
}

function CheckProductCode($code) 
{
    $res = mysql_fetch_assoc(mysql_query("	SELECT	`id`
										 	FROM	`production`
										  	WHERE	`code` = '$code' && `actived` = 1"));
	if($res['id'] != ''){
		return true;
	}
	return false;
}

function DisableProduct($prod_id)
{
	mysql_query("UPDATE `production`
				 SET	`actived` = 0
				 WHERE	`id` = $prod_id ");
    
  }

function DeleteImage($prod_id)
{
	mysql_query("UPDATE
	    			`production`
				 SET
				    `image`			= NULL
				 WHERE
					`id`			= $prod_id");
	
}

function Get_model($point)
{
	$data = '';
	$req = mysql_query("SELECT `id`, `name`
						FROM `model`
						WHERE model.actived=1");

	$data = '<option value="0" selected="selected">----</option>';

	while( $res = mysql_fetch_assoc($req)){
		if($res['id'] == $point){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}
	}

	return $data;
}

function Getprod_category($point)
{
	$data = '';
	$req = mysql_query("SELECT `id`, `name`
						FROM `production_category`");

	$data = '<option value="0" selected="selected">----</option>';

	while( $res = mysql_fetch_assoc($req)){
		if($res['id'] == $point){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}
	}

	return $data;
}

function Get_brand($point)
{
	$data = '';
	$req = mysql_query("SELECT `id`, `name`
						FROM `brand`
						WHERE brand.actived=1");

	$data = '<option value="0" selected="selected">----</option>';
	while( $res = mysql_fetch_assoc($req)){
		if($res['id'] == $point){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}
	}

	return $data;
}

function Get_unit($point)
{
	$data = '';
	$req = mysql_query("SELECT `id`, `name`
						FROM `production_unit`
						WHERE production_unit.actived=1");

	$data = '<option value="0" selected="selected">----</option>';
	while( $res = mysql_fetch_assoc($req)){
		if($res['id'] == $point){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}
	}

	return $data;
}

function GetCategory($point)
{
	$data = '';
	
	$data = '<option value="0" selected="selected"></option>';	
	$tree = new CategoryTree($point);	
	$data .= $tree->GetData();
	
	return $data;
}

function GetProduct($prod_id) 
{
    $res = mysql_fetch_assoc(mysql_query("	SELECT	production.id,
													production.`code`,
													production.`barcode`,
													production.`name`,
    												production.`category`,
													production.`engine`,
													production.`engine_capacity`,
													production.`size`,
													production.`brand_id`,
													production.`born_date`,
													production.`model`,
													production.`comment`,
    												production.`unit`,
													production.`image`
											FROM	`production`
											WHERE	`id` = $prod_id"));
	return $res;
}

function GetPage($res = '')
{
	$image = $res[image];
	if(empty($image)){
		$image = '0.jpg';
	}
	$data = '		
	<div id="dialog-form">
		<fieldset style="width: 350px; float: left;">
	    	<legend>ძირითადი ინფორმაცია</legend>

	    	<table class="dialog-form-table">
				<tr>
					<td style="width: 170px;"><label for="code">შიდა კოდი</label></td>
					<td>
						<input type="text" id="code" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['code'] . '" />
					</td>
				</tr>	
	    		<tr>
					<td style="width: 170px;"><label for="code">კოდი</label></td>
					<td>
						<input type="text" id="barcode" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['barcode'] . '" />
					</td>
				</tr>								
				<tr>
					<td style="width: 170px;"><label for="name">პროდუქტი</label></td>
					<td>
						<input type="text" id="name" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['name'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="category">კატეგორია</label></td>
					<td>
						
						<select id="category" class="idls">' . Getprod_category($res[category]) . '</select>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="category">მოდელი</label></td>
					<td>
						<select id="model" class="idls">' . Get_model($res[model]) . '</select>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="category">ძრავი</label></td>
					<td>
						<input type="text" id="engine" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['engine'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="unit">კუბატურა</label></td>
					<td>
						<input type="text" id="engine_capacity" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['engine_capacity'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="unit">ზომა</label></td>
					<td>
						<input type="text" id="size" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['size'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="category">ერთეული</label></td>
					<td>
						<select id="unit" class="idls">' . Get_unit($res[unit]) . '</select>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="unit">წლები</label></td>
					<td>
						<input type="text" id="born_date" class="idle" onblur="this.className=\'idle\'" value="' . $res['born_date'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="category">ბრენდი</label></td>
					<td>
						<select id="brand_id" class="idls">' . Get_brand($res[brand_id]) . '</select>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="unit">შენიშვნა</label></td>
					<td>
						<textarea id="comment" class="idle large" cols="30" rows="1" style="width:159px !important; height:50px !important;">' . $res['comment'] . '</textarea>
					</td>
				</tr>
			</table>
        </fieldset>
								
 	    <fieldset style="width: 350px;">
	    	<legend>პროდუქტის სურათი</legend>
			
	    	<table class="dialog-form-table" width="100%">
	    		<tr>
					<td id="img_colum" colspan="2">
						<img id="upload_img" src="media/uploads/images/production/' . $image . '">
					</td>
				</tr>
				<tr><!-- Upload Image -->
					<td id="act">
						<span>
							<a href="#" id="view_image" class="complate">View</a> | <a href="#" id="delete_image" class="delete">Delete</a>
						</span>
					</td>
					<td>
						<div class="file-uploader">
							<input id="choose_file" type="file" name="choose_file" class="input" style="display: none;">
							<button id="choose_button" class="center">აირჩიეთ ფაილი</button>
						</div>
					</td>
				</tr>
			</table>
        </fieldset>
		<div class="clear"></div>
								
								
			
												
		<!-- ID -->
		<input type="hidden" id="prod_id" value="' . $res['id'] . '" />
    </div>
    
    ';
	return $data;
}

?>